package com.aijk.ehm.sys.api;

import com.aijk.ehm.sys.model.dto.SysRoleCreateDto;
import com.aijk.ehm.sys.model.qo.SysRoleQo;
import com.aijk.ehm.sys.model.SysRole;
import com.aijk.ehm.sys.model.SysRoleAuth;
import com.aijk.ehm.sys.model.qo.RoleAuthQo;
import com.aijk.ehm.sys.service.SysRoleAuthService;
import com.aijk.ehm.sys.service.SysRoleService;
import com.aijk.base.entity.PagingRequest;
import com.aijk.commons.exception.ErrorCodeException;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>  </p>
 * User: chendw
 * Date: 2016/11/15 17:30
 */
@Service("sysRoleApi")
public class SysRoleApiImpl implements SysRoleApi {

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysRoleAuthService authService;

    @Override
    public PageInfo<SysRole> getPage(SysRoleQo qo) throws ErrorCodeException {
        PagingRequest pagingRequest = new PagingRequest(qo.getPageNo().intValue(), qo.getPageSize().intValue());
        return roleService.getPageInfo(pagingRequest, qo);
    }

    @Override
    public SysRole get(Integer roleId) throws ErrorCodeException {
        return roleService.get(roleId);
    }

    @Override
    public List<SysRole> getList(SysRoleQo qo) throws ErrorCodeException {
        return roleService.findAll(qo);
    }

    @Override
    public SysRole save(SysRoleCreateDto dto) throws ErrorCodeException {
        SysRole retRole;
        Boolean isSave=false;
        if (dto.getRoleId() != null) {
            RoleAuthQo qo = new RoleAuthQo();
            qo.setRid(dto.getRoleId());
            List<SysRoleAuth> auths = authService.find(qo);
            List<Integer> midList = new ArrayList<>();
            for (SysRoleAuth auth:auths){
                midList.add(auth.getMid());
            }

            List<Integer> permList = new ArrayList<>();
            String[] moudlesIds = dto.getPermIds().split(",");
            for (String mid:moudlesIds){
                permList.add(Integer.parseInt(mid));
            }
            if(!midList.containsAll(permList) ||! permList.containsAll(midList)){
                authService.delRoleAuth(dto.getRoleId());
                isSave =true;
            }

            retRole = roleService.update(dto);
        } else {
            isSave=true;
            retRole = roleService.insert(dto);
        }
        // 保存权限
        if(isSave)
        authService.saveRoleAuth(retRole.getRoleId(), dto.getPermIds());
        return retRole;
    }


    @Override
    public int delete(Integer roleId) throws ErrorCodeException {
        authService.delRoleAuth(roleId);
        return roleService.delete(roleId);
    }

}
